package tt.dz.mvc.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

import tt.dz.entity.base.JsonCommon;
import tt.dz.service.sys.OtherPartnerService;
import tt.dz.util.OmsConstant.MsgCodeEnum;

//@WebFilter(
//		filterName="openApiFilter",
//urlPatterns = { "/openApi/*" }, 
//initParams = { 
//		@WebInitParam(name = "noFilterUrls", value = "userApi/login"),
//		@WebInitParam(name = "loginPath", value = "login.html"),
//})
public class PartnerLoginFilter implements Filter{

	private  OtherPartnerService otherPartnerService;
	@Override
	public void destroy() 
	{
		
		
	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest)arg0;
		HttpServletResponse response = (HttpServletResponse)arg1;
		//获取第三方用户认证信息
		String authorizationToken = request.getHeader("AuthorizationToken");
		String url = request.getRequestURI();
		JsonCommon<?> jc = otherPartnerService.partnerOpenApiAuthorization(authorizationToken, url);
		if (MsgCodeEnum.SUCCESS.getMsgCode().equals(jc.getCode()))
		{
			arg2.doFilter(arg0, arg1);
		}
		else
		{
			response.setStatus(403);
			response.setCharacterEncoding("utf-8");
			PrintWriter writer = response.getWriter();
			writer.print(JSON.toJSONStringWithDateFormat(jc, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteDateUseDateFormat));
			writer.flush();
		}
		
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException 
	{
		ServletContext servletContext = arg0.getServletContext();  
        WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        otherPartnerService = ctx.getBean(OtherPartnerService.class);
	}

}
